// by Xeno

// PlayerSpawn is only called when the player dies (through the Killed Event and the CheckKill.sqf script), to set everything back alright.
// This includes action menus, etc.
// Initially, the player is set by the SetupPlayer script and not by the PlayerSpawn script.
#define __prma player removeAction _id
#define __adddrop player setVariable [#d_dropaction, player addAction [localize "MSG_DOM_ACTIONCALLDROP" call XGreyText, "client\calldrop.sqf",[],-1,false]]
private ["_weapons", "_magazines", "_hasruck", "_ruckmags", "_ruckweapons", "_backwep", "_types", "_type", "_action", "_ar", "_primw", "_muzzles", "_s", "_items"];

_weapons = weapons player;
_magazines = magazines player;
_items = items player;
if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3: %4, %5, %6",diag_tickTime,"playerspawn.sqf","Gear",_weapons,_magazines,_items]; };
_oabackpackmags = [[],[]];
_oabackpackweaps = [[],[]];
_ubackp = "";
if (requiredVersion "1.59" ) then {
	_ubp = unitBackpack player;
	_ubackp = if (!isNull _ubp) then {typeOf _ubp} else {""};
	if (_ubackp != "") then {
		_oabackpackmags = getMagazineCargo _ubp;
		_oabackpackweaps = getWeaponCargo _ubp;
	};
	if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3: %4, %5, %6",diag_tickTime,"playerspawn.sqf","Backpack Saved",_ubackp,_oabackpackmags,_oabackpackweaps]; };
};


if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"playerspawn.sqf","Waiting for player to be alive again"]; };
// This waits until the R3F_Revive kicks in.
waituntil {alive player};
sleep ((random 2) + 1);
// Avoids having two threads running in parallel
waituntil {!d_player_spawn_started};
if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3 (%4)",diag_tickTime,"playerspawn.sqf","Starting setting all variables, menus and the rest",getPos player]; };

d_player_spawn_started = true;
d_player_busy_building = false;

// In SetupPlayer if we had created an action, we use the code below to remove it.
if (d_player_can_call_drop) then {
	_id = player getVariable "d_dropaction";
	if (_id != -8878) then {
		__prma;
		player setVariable  ["d_dropaction", -8878];
	};
};


If (d_string_player in d_is_radiooperator) then {
	d_heli_taxi_available = true;
	// Removed the check for an available airtaxi. It is checked inside the dialog
	// If (WithAirTaxi) then { player addaction [localize "MSG_DOM_ACTIONCALLTAXI" call XGreyText,"client\airtaxi2.sqf",[],0,False,True,"","call XfAirTaxiAvailable;"]; };
	If (WithAirTaxi) then { player addaction [localize "MSG_DOM_ACTIONCALLTAXI" call XGreyText,"client\airtaxi2.sqf",[],0,False,True,"","true"]; };
};

if (d_bag_fences_per_player > 0) then {
	player setVariable ["d_bagfenceaction_round", player addAction [localize "MSG_DOM_ACTIONROUNDFENCE" call XGreenText, "client\bagfence.sqf","ROUND",-1,false]];
	player setVariable ["d_bagfenceaction_short", player addAction [localize "MSG_DOM_ACTIONSHORTFENCE" call XGreenText, "client\bagfence.sqf","SHORT",-1,false]];
	if (d_string_player in d_is_engineer) then {
		player setVariable ["d_bagfenceaction_short", player addAction [localize "MSG_DOM_ACTIONHBARRIER" call XGreenText, "client\bagfence.sqf","CUBE",-1,false]];
	};
	player setVariable ["d_bagfences", 0];
};

if (WithBackpack) then {
	_id = player getVariable "d_pbp_id";
	if (_id != -9999) then {
		if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3 (%4)",diag_tickTime,"playerspawn.sqf","Removing backpack",_id]; };
		player removeAction _id;
		player setVariable ["d_pbp_id", -9999];
	};
};

// In SetupPlayer if we had created an action, we use the code below to remove it.
if (d_player_is_medic) then {
	_id = player getVariable "d_medicaction";
	if (_id != -3333) then {
		__prma;
		player setVariable ["d_medicaction", -3333];
	};
};

// In SetupPlayer if we had created an action, we use the code below to remove it.
if (d_with_mgnest) then {
	if (d_player_can_build_mgnest) then {
		_id = player getVariable "d_mgnestaction";
		if (_id != -11111) then {
			__prma;
			player setVariable ["d_mgnestaction", -11111];
		};
	};
};

// In SetupPlayer if we had created an action, we use the code below to remove it.
if (d_with_aapod) then {
	if (d_player_can_build_aapod) then {
		_id = player getVariable "d_aapodaction";
		if (_id != -22222) then {
			__prma;
			player setVariable ["d_aapodaction", -22222];
		};
	};
};

if (!isNil "LHD_Center") then {
	[] spawn {
		_elevators = player getVariable "elevators_actions";
		if (isnil "_elevators") then {_elevators=[];};
		{
			player removeAction _x;
		} foreach _elevators;
	};
};

// This action is to allow HALO Jumps from vehicles.
// Not needed since we use a trigger now
// player addAction [localize "MSG_DOM_VECHALOJUMP" call XGreyText,"client\halo.sqf",[],-1,false,true,"","vehicle player != player && ((vehicle player) call XfGetHeight) > 500"];

// Those are the special optional menus, listed in i_client if there are any.
if (!isNil "d_action_menus_type") then {
	if (count d_action_menus_type > 0) then {
		{
			_types = _x select 0;
			if (count _types > 0) then {
				if (_type in _types) then {
					_id = _x select 3;
					__prma;
				};
			} else {
				_id = _x select 3;
				__prma;
			};
		} forEach d_action_menus_type;
	};
};
// Those are the special optional menus, listed in i_client if there are any.
if (!isNil "d_action_menus_unit") then {
	if (count d_action_menus_unit > 0) then {
		{
			_types = _x select 0;
			_ar = _x;
			if (count _types > 0) then {
				{
					_hh = missionNamespace getVariable _x;
					if (player ==  _hh) exitWith { 
						_id = _ar select 3;
						__prma;
					};
				} forEach _types
			} else {
				_id = _x select 3;
				__prma;
			};
		} forEach d_action_menus_unit;
	};
};

// This waits until the R3F_Revive kicks in.
waitUntil {alive player};

// TODO : comes from init.sqf and it until now deactivated. It makes the player invincible, but I doubt I actually need it.
//if (!isNil {__pGetVar(d_p_ev_hd)}) then {d_phd_invulnerable = true};

// We set back all the action menus

if (d_player_can_call_drop) then {__adddrop};

if (d_player_is_medic) then {
	if (player getVariable "d_medicaction" == -3333) then {
		player setVariable ["d_medicaction", player addAction [localize "MSG_DOM_ACTIONBUILDMASH" call XGreyText, "client\mash.sqf",[],-1,false]];
	};
};
if (d_with_mgnest) then {
	if (d_player_can_build_mgnest) then {
		if (player getVariable "d_mgnestaction" == -11111) then {
			player setVariable ["d_mgnestaction", player addAction [localize "MSG_DOM_ACTIONBUILDMGNEST" call XGreyText, "client\mgnest.sqf",[],-1,false]];
		};
	};
};
if (d_with_aapod) then {
	if (d_player_can_build_aapod) then {
		if (player getVariable "d_aapodaction" == -22222) then {
			player setVariable ["d_aapodaction", player addAction [localize "MSG_DOM_ACTIONBUILDAA" call XGreyText, "client\aapod.sqf",[],-1,false]];
		};
	};
};

if (!isNil "d_action_menus_type") then {
	if (count d_action_menus_type > 0) then {
		{
			_types = _x select 0;
			if (count _types > 0) then {
				if (_type in _types) then { 
					_action = player addAction [(_x select 1) call XGreyText,_x select 2,[],-1,false];
					_x set [3, _action];
				};
			} else {
				_action = player addAction [(_x select 1) call XGreyText,_x select 2,[],-1,false];
				_x set [3, _action];
			};
		} forEach d_action_menus_type;
	};
};
if (!isNil "d_action_menus_unit") then {
	if (count d_action_menus_unit > 0) then {
		{
			_types = _x select 0;
			_ar = _x;
			if (count _types > 0) then {
				{
					_hh = missionNamespace getVariable _x;
					if (player ==  _hh) exitWith { 
						_action = player addAction [(_ar select 1) call XGreyText,_ar select 2,[],-1,false];
						_ar set [3, _action];
					};
				} forEach _types
			} else {
				_action = player addAction [(_x select 1) call XGreyText,_x select 2,[],-1,false];
				_x set [3, _action];
			};
		} forEach d_action_menus_unit;
	};
};
if (!isNil {player getVariable "d_bike_created"}) then {player setVariable ["d_bike_created", false]};

// We wait that the revive dialog is closed or the player got killed again waiting for a revive (it happens....)
waitUntil {!dialog || !alive player};
sleep 5;
d_player_spawn_started = false;
player setVariable ["DamageChart",[[],[]]];
 
If (d_revive_script != "R3F") then {
	// diag_log Format["(%1)[%2]: %3: %4, %5, %6",diag_tickTime,"playerSpawn.sqf","Rearming",_weapons,_magazines,_items];
	removeAllItems player;
	removeAllWeapons player;
	{player addMagazine _x;} forEach _magazines;
	{player addWeapon _x;} forEach _weapons;
	{if !(player hasWeapon _x) then {player addWeapon _x}} forEach _items;
	// if (count d_backpack_helper > 0) then {
		// {__addmx} forEach (d_backpack_helper select 0);
		// {__addwx} forEach (d_backpack_helper select 1);
		// d_backpack_helper = [];
	// };
	// diag_log Format["(%1)[%2]: %3: %4, %5",diag_tickTime,"playerSpawn.sqf","Rearmed",weapons player,magazines player];
};

if (!isnil "_ubackp" && _ubackp != "" && requiredVersion "1.59" ) then {
	if (!isNull (unitBackpack player)) then {removeBackpack player};
	player addBackpack _ubackp;
	_bp = unitBackpack player;
	clearMagazineCargo _bp;
	clearWeaponCargo _bp;
	if (count (_oabackpackmags select 0) > 0) then {
		_mags = _oabackpackmags select 0;
		_mcount = _oabackpackmags select 1;
		{_bp addMagazineCargo [_x, _mcount select _forEachIndex]} forEach _mags;
	};
	if (count (_oabackpackweaps select 0) > 0) then {
		_weaps = _oabackpackweaps select 0;
		_mcount = _oabackpackweaps select 1;
		{_bp addWeaponCargo [_x, _mcount select _forEachIndex]} forEach _weaps;
	};
	if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3: %4, %5, %6",diag_tickTime,"playerspawn.sqf","Backpack Restored",_ubackp,_oabackpackmags,_oabackpackweaps]; };
};


if (!isNil "LHD_Center") then {
	[] spawn {
		waituntil {typename (["LHD_Teleporter_Landing",False] call XNetGetJIP) != "BOOLEAN"};
		_lhd = ["LHD_Teleporter_Landing",ObjNull] call XNetGetJIP;
		If (!isNull _lhd) then {
			_elevators = [];
			_elevator = ["LHD_Elevator_1",objNull] call XNetGetJIP;
			_id = player addAction [localize "MSG_DOM_LOWERELEVATOR", "client\lhdelevator.sqf", [_elevator,0], 1, True, False, "", "(((getPosASL (['LHD_Elevator_1'] call XNetGetJIP)) select 2) > -10) && (([player,(['LHD_Elevator_1_pos'] call XNetGetJIP)] call XfDistTo) < 15)"];
			_elevators set [0,_id];
			_id = player addAction [localize "MSG_DOM_RAISEELEVATOR", "client\lhdelevator.sqf", [_elevator,1], 1, True, False, "", "(((getPosASL (['LHD_Elevator_1'] call XNetGetJIP)) select 2) < -4) && (([player,(['LHD_Elevator_1_pos'] call XNetGetJIP)] call XfDistTo) < 15)"];
			_elevators set [1,_id];
			_elevator = ["LHD_Elevator_2",objNull] call XNetGetJIP;
			_id = player addAction [localize "MSG_DOM_LOWERELEVATOR", "client\lhdelevator.sqf", [_elevator,0], 1, True, False, "", "(((getPosASL (['LHD_Elevator_2'] call XNetGetJIP)) select 2) > -10) && (([player,(['LHD_Elevator_2_pos'] call XNetGetJIP)] call XfDistTo) < 15)"];
			_elevators set [2,_id];
			_id = player addAction [localize "MSG_DOM_RAISEELEVATOR", "client\lhdelevator.sqf", [_elevator,1], 1, True, False, "", "(((getPosASL (['LHD_Elevator_2'] call XNetGetJIP)) select 2) < -4) && (([player,(['LHD_Elevator_2_pos'] call XNetGetJIP)] call XfDistTo) < 15)"];
			_elevators set [3,_id];
			player setVariable ["elevators_actions",_elevators];
		};
	};
};

execVM "missions\mission_init.sqf";
player addAction [localize "MSG_DOM_ACTIONSHOWSTATUS" call XLightGreenText, "client\showstatus.sqf", [],1,False,True,"","true"];
if (WithBackpack) then {
	if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3: %4 %5",diag_tickTime,"playerspawn.sqf","With Backpack",(player GetVariable "d_pbp_id"),(player GetVariable "d_player_backpack")]; };
	if (count (player GetVariable "d_player_backpack") == 0) then {
		if (primaryWeapon player != "" && primaryWeapon player != " ") then {
			_s = format [localize "MSG_DOM_ACTIONBACKPACKTO", [primaryWeapon player,1] call XfGetDisplayName];
			if ((player GetVariable "d_pbp_id") == -9999) then {
				player SetVariable ["d_pbp_id", player addAction [_s call XGreyText, "client\backpack.sqf",[],-1,false]]
			};
		};
		if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3 (%4)",diag_tickTime,"playerspawn.sqf","Empty backpack added",(player GetVariable "d_pbp_id")]; };
	} else {
		_s = format [localize "MSG_DOM_ACTIONBACKPACKFROM", [(player GetVariable "d_player_backpack") select 0,1] call XfGetDisplayName];
		if ((player GetVariable "d_pbp_id") == -9999) then {
			player SetVariable ["d_pbp_id", player addAction [_s call XGreyText, "client\backpack.sqf",[],-1,false]]
		};
		if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3 (%4)",diag_tickTime,"playerspawn.sqf","Existing backpack added",(player GetVariable "d_pbp_id")]; };
	};
};

if (d_global_debug > 9) then { 
	diag_log Format["JIPH mr1_in_air %1",(["mr1_in_air","empty"] call XNetGetJIP)];
	diag_log Format["JIPH mr2_in_air %1",(["mr2_in_air","empty"] call XNetGetJIP)];
	diag_log Format["JIPH ammo_boxes %1",(["ammo_boxes","empty"] call XNetGetJIP)];
	diag_log Format["JIPH sec_kind %1",(["sec_kind","empty"] call XNetGetJIP)];
	diag_log Format["JIPH d_ammo_boxes %1",(["d_ammo_boxes","empty"] call XNetGetJIP)];
	diag_log Format["JIPH para_available %1",(["para_available","empty"] call XNetGetJIP)];
	diag_log Format["JIPH current_target_position %1",(["current_target_position","empty"] call XNetGetJIP)];
	diag_log Format["JIPH available_drop_vehicles %1",(["available_drop_vehicles","empty"] call XNetGetJIP)];
	diag_log Format["JIPH X_DropZone %1",(["X_DropZone","empty"] call XNetGetJIP)];
};